package cz.patamat.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cz.patamat.support.EmailDataStorage;
import cz.patamat.support.EmailValidator;

/**
 * Add subscriber email address to storage.
 *
 */
@SuppressWarnings("serial")
public class AddSubscriberServlet extends HttpServlet {
	
	private static EmailValidator emailValidator = new EmailValidator();
	
	private static EmailDataStorage dataStorage = new EmailDataStorage();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher(ShowProtowebServlet.PROMOWEB_URL).forward(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String emailAddress = req.getParameter("mail");
		if (emailAddress.isEmpty()) {
			req.setAttribute("emptyEmailAddressError", true);
			req.getRequestDispatcher(ShowProtowebServlet.PROMOWEB_URL).forward(req, resp);
			return;
		}
		if (!emailValidator.validate(emailAddress)) {
			req.setAttribute("invalidEmailAddressError", true);
			req.setAttribute("mail", emailAddress);
			req.getRequestDispatcher(ShowProtowebServlet.PROMOWEB_URL).forward(req, resp);
			return;
		}
		
		dataStorage.saveSubscriber(emailAddress);
		
		req.setAttribute("successSubscription", true);
		req.getRequestDispatcher(ShowProtowebServlet.PROMOWEB_URL).forward(req, resp);
	}

}
